<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>镜头控制器</title>
    <style>
        :root {
            --primary-color: #FFB300;
            --secondary-color: #FFD54F;
            --dark-bg: #121212;
            --darker-bg: #1e1e1e;
            --text-color: #ffffff;
            --border-color: #333333;
            --accent-color: #4CAF50;
            --warning-color: #FF9800;
            --error-color: #F44336;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--dark-bg);
            color: var(--text-color);
            display: flex;
            height: 100vh;
            overflow: auto;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            width: 100%;
            gap: 20px;
            padding: 20px;
            min-height: 100vh;
            flex: 1;
        }

        /* 添加底部内边距确保内容不被截断 */
        .container > * {
            margin-bottom: 20px;
        }

        .left-panel {
            flex: 0 0 400px;
            display: flex;
            flex-direction: column;
            gap: 0;
        }

        .right-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .panel {
            background-color: var(--darker-bg);
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
        }

        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .panel-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-color);
        }

        .panel-actions {
            display: flex;
            gap: 8px;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
            border: none;
            outline: none;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: #000;
        }

        .btn-primary:hover {
            background-color: var(--secondary-color);
        }

        .btn-secondary {
            background-color: #333;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #444;
        }

        .image-container {
            position: relative;
            width: 100%;
            height: 300px;
            background-color: #222;
            border-radius: 8px;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .image-container img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .image-placeholder {
            color: #888;
            text-align: center;
            padding: 20px;
        }

        .upload-area {
            border: 2px dashed #555;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .upload-area:hover {
            border-color: var(--primary-color);
            background-color: rgba(255, 179, 0, 0.1);
        }

        .upload-icon {
            font-size: 36px;
            margin-bottom: 10px;
            color: var(--primary-color);
        }

        .camera-controls {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .camera-controls-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .camera-controls-grid .control-group {
            margin-bottom: 0;
        }

        @media (max-width: 768px) {
            .camera-controls-grid {
                grid-template-columns: 1fr;
            }
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .control-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
        }

        .slider-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .slider {
            flex: 1;
            height: 6px;
            border-radius: 3px;
            background: #444;
            position: relative;
        }

        .slider::-webkit-slider-thumb {
            appearance: none;
            height: 16px;
            width: 16px;
            border-radius: 50%;
            background: var(--primary-color);
            cursor: pointer;
            border: 2px solid #000;
            transition: all 0.2s ease;
        }

        .slider::-moz-range-thumb {
            height: 16px;
            width: 16px;
            border-radius: 50%;
            background: var(--primary-color);
            cursor: pointer;
            border: 2px solid #000;
            transition: all 0.2s ease;
        }

        .value-input {
            width: 60px;
            padding: 6px 8px;
            border-radius: 6px;
            border: 1px solid #555;
            background: #222;
            color: white;
            text-align: center;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .checkbox {
            width: 18px;
            height: 18px;
            border: 2px solid #555;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        .checkbox.checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .checkbox-icon {
            color: #000;
            font-size: 12px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #aaa;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #555;
        }

        .status-dot.processing {
            background-color: var(--warning-color);
            animation: pulse 1.5s infinite;
        }

        .status-dot.success {
            background-color: var(--accent-color);
        }

        .status-dot.error {
            background-color: var(--error-color);
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .prompt-display {
            background-color: #222;
            border-radius: 8px;
            padding: 15px;
            min-height: 120px;
            font-size: 14px;
            line-height: 1.6;
            overflow-y: auto;
            resize: vertical;
        }

        .prompt-textarea {
            width: 100%;
            height: 120px;
            background-color: #333;
            border: 1px solid #555;
            border-radius: 6px;
            color: white;
            padding: 10px;
            font-family: monospace;
            font-size: 13px;
            line-height: 1.5;
            resize: vertical;
            outline: none;
        }

        .prompt-textarea:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 5px rgba(255, 179, 0, 0.3);
        }

        .prompt-line {
            margin-bottom: 8px;
            padding: 4px 0;
            border-bottom: 1px solid #333;
        }

        .prompt-line:last-child {
            border-bottom: none;
        }

        .chinese-text {
            color: #FFB300;
            font-weight: 500;
        }

        .english-text {
            color: #aaa;
            margin-left: 10px;
        }

        .control-line {
            opacity: 0.7;
            transition: opacity 0.2s ease;
        }

        .control-line.active {
            opacity: 1;
        }

        .result-image {
            width: 100%;
            height: 550px;
            border-radius: 8px;
            object-fit: contain;
            background-color: #222;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .result-image img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .video-button {
            width: 100%;
            padding: 15px;
            background-color: var(--primary-color);
            color: #000;
            border-radius: 8px;
            font-weight: 600;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-top: 15px;
        }

        .video-button:hover {
            background-color: var(--secondary-color);
        }

        .api-status {
            margin-top: 10px;
            padding: 10px;
            background-color: #222;
            border-radius: 8px;
            font-size: 14px;
            word-break: break-all;
        }

        .loading-spinner {
            width: 24px;
            height: 24px;
            border: 3px solid #444;
            border-top: 3px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .hidden {
            display: none;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                padding: 10px;
            }

            .left-panel {
                flex: 0 0 auto;
                width: 100%;
                gap: 20px;
            }

            .right-panel {
                flex: 1;
                width: 100%;
            }

            .image-container, .result-image {
                height: 200px;
            }
        }

        .file-input {
            display: none;
        }

        .preview-container {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .preview-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .preview-container:hover .preview-overlay {
            opacity: 1;
        }

        .preview-action {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            margin: 0 5px;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .preview-action:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .info-text {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
            text-align: center;
        }

        .api-response {
            margin-top: 15px;
            padding: 15px;
            background-color: #222;
            border-radius: 8px;
            font-size: 14px;
            line-height: 1.5;
            overflow-x: auto;
            max-height: 300px;
            overflow-y: auto;
        }

        .api-response pre {
            margin: 0;
            font-family: monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .api-status.success {
            color: #4CAF50;
        }

        .api-status.error {
            color: #F44336;
        }

        .api-status.processing {
            color: #FF9800;
        }

        .time-indicator {
            font-size: 12px;
            color: #888;
            text-align: right;
            margin-top: 5px;
        }

        .progress-bar {
            height: 4px;
            background: #333;
            border-radius: 2px;
            margin-top: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: var(--primary-color);
            width: 0%;
            transition: width 0.3s ease;
        }

        .tooltip {
            position: absolute;
            background: #333;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 100;
            opacity: 0;
            transition: opacity 0.2s ease;
            pointer-events: none;
        }

        .slider-container:hover .tooltip {
            opacity: 1;
        }

        /* 图片模态框样式 */
        #imageModal {
            animation: fadeIn 0.3s ease;
        }

        #imageModal .preview-overlay {
            display: none;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* 移动端模态框适配 */
        @media (max-width: 768px) {
            #imageModal {
                padding: 10px;
            }

            #imageModal .preview-overlay {
                display: none;
            }
        }

        /* 通知消息动画 */
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left-panel">
            <div class="panel">
                <div class="panel-header">
                    <div class="panel-title">输入图像</div>
                    <div class="panel-actions">
                        <button class="btn btn-secondary" id="resetBtn">🔄</button>
                        <button class="btn btn-secondary" id="closeBtn">✕</button>
                    </div>
                </div>
                <div class="image-container" id="inputImageContainer">
                    <div class="image-placeholder" id="imagePlaceholder">
                        <div>📁</div>
                        <div>点击上传图片或拖拽图片到此处</div>
                    </div>
                </div>
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📤</div>
                    <div>点击上传图片</div>
                    <input type="file" id="fileInput" class="file-input" accept="image/*">
                </div>

                <div class="url-section" style="margin-top: 15px;">
                    <label for="urlInput" style="display: block; margin-bottom: 8px; font-size: 14px; color: #ccc;">或输入网络图片 URL:</label>
                    <div style="display: flex; gap: 8px;">
                        <input type="url" id="urlInput" placeholder="https://example.com/image.jpg" style="flex: 1; padding: 8px; background-color: #222; border: 1px solid #555; border-radius: 6px; color: white; font-size: 13px;">
                        <button id="loadUrlBtn" class="btn btn-secondary" style="padding: 8px 16px;">加载</button>
                    </div>
                    <div class="info-text" id="urlStatus" style="margin-top: 5px; display: none;"></div>
                </div>
            </div>

            <div class="panel" style="margin-top: 20px;">
                <div class="panel-header">
                    <div class="panel-title">文字提示词Prompt</div>
                </div>
                <div class="prompt-display" id="promptDisplay">
                    <div class="prompt-textarea" id="promptTextarea" contenteditable="true" placeholder="调整摄像机控制器，这里将显示对应的文字提示词，也可以手动编辑..."></div>
                </div>
            </div>

            <div class="panel" style="margin-top: 20px;">
                <div class="panel-header">
                    <div class="panel-title">API 配置</div>
                </div>
                <div style="margin-bottom: 10px;">
                    <label for="apiKeyInput" style="display: block; margin-bottom: 8px; font-size: 14px; color: #ccc;">API 密钥:</label>
                    <input type="password" id="apiKeyInput" placeholder="请输入BizyAIR API密钥" style="width: 100%; padding: 8px; background-color: #222; border: 1px solid #555; border-radius: 6px; color: white; font-size: 13px;">
                    <button id="saveApiKeyBtn" class="btn btn-secondary" style="margin-top: 8px; width: 100%;">保存 API 密钥</button>
                </div>
            </div>
        </div>

        <div class="right-panel">
            <div class="panel">
                <div class="panel-header">
                    <div class="panel-title">摄像机控制</div>
                </div>
                <div class="camera-controls">
                    <div class="camera-controls-grid">
                        <div class="control-group">
                            <div class="control-label">
                                <span>向左↔向右</span>
                                <div class="value-input-container">
                                    <input type="number" class="value-input" id="horizontalInput" value="0" min="-1" max="1">
                                    <button class="btn btn-secondary reset-btn" data-target="horizontalInput">↻</button>
                                </div>
                            </div>
                            <div class="slider-container">
                                <input type="range" class="slider" id="horizontalSlider" min="-1" max="1" value="0">
                                <div class="tooltip" id="horizontalTooltip">0</div>
                            </div>
                        </div>

                        <div class="control-group">
                            <div class="control-label">
                                <span>向下↔向上</span>
                                <div class="value-input-container">
                                    <input type="number" class="value-input" id="verticalMoveInput" value="0" min="-1" max="1">
                                    <button class="btn btn-secondary reset-btn" data-target="verticalMoveInput">↻</button>
                                </div>
                            </div>
                            <div class="slider-container">
                                <input type="range" class="slider" id="verticalMoveSlider" min="-1" max="1" value="0">
                                <div class="tooltip" id="verticalMoveTooltip">0</div>
                            </div>
                        </div>

                        <div class="control-group">
                            <div class="control-label">
                                <span>左右旋转</span>
                                <div class="value-input-container">
                                    <input type="number" class="value-input" id="rotateInput" value="0" min="-90" max="90">
                                    <button class="btn btn-secondary reset-btn" data-target="rotateInput">↻</button>
                                </div>
                            </div>
                            <div class="slider-container">
                                <input type="range" class="slider" id="rotateSlider" min="-90" max="90" value="0">
                                <div class="tooltip" id="rotateTooltip">0°</div>
                            </div>
                        </div>

                        <div class="control-group">
                            <div class="control-label">
                                <span>前进→特写</span>
                                <div class="value-input-container">
                                    <input type="number" class="value-input" id="moveInput" value="0" min="0" max="10">
                                    <button class="btn btn-secondary reset-btn" data-target="moveInput">↻</button>
                                </div>
                            </div>
                            <div class="slider-container">
                                <input type="range" class="slider" id="moveSlider" min="0" max="10" value="0">
                                <div class="tooltip" id="moveTooltip">0</div>
                            </div>
                        </div>

                        <div class="control-group">
                            <div class="control-label">
                                <span>垂直角度（俯视↔仰视）</span>
                                <div class="value-input-container">
                                    <input type="number" class="value-input" id="verticalInput" value="0" min="-1" max="1">
                                    <button class="btn btn-secondary reset-btn" data-target="verticalInput">↻</button>
                                </div>
                            </div>
                            <div class="slider-container">
                                <input type="range" class="slider" id="verticalSlider" min="-1" max="1" value="0">
                                <div class="tooltip" id="verticalTooltip">0</div>
                            </div>
                        </div>

                        <div class="control-group">
                            <div class="checkbox-container" id="wideAngleCheckbox">
                                <div class="checkbox">
                                    <div class="checkbox-icon">✓</div>
                                </div>
                                <span>广角镜头</span>
                            </div>
                        </div>
                    </div>

                    <div class="action-buttons">
                        <button class="btn btn-secondary" id="resetAllBtn">重置</button>
                        <button class="btn btn-primary" id="generateBtn">🎨 生成图像</button>
                    </div>
                </div>
            </div>

            <div class="panel">
                <div class="panel-header">
                    <div class="panel-title">生成结果</div>
                    
                <div class="time-indicator" id="timeIndicator" style="display: none;">processing | 0.0/3.9s</div>
                <div class="progress-bar" style="display: none;">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                </div>
                <div class="result-image" id="resultImageContainer">
                    <div class="image-placeholder">
                        <div>🖼️</div>
                        <div>等待生成结果...</div>
                    </div>
                </div>
                <div class="api-status" id="apiStatus">
                    API 状态: 待处理
                </div>
            </div>

            <div class="video-button" id="createVideoBtn">
                🎬 图像首尾帧创建视频
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let selectedImage = null;
        let isProcessing = false;
        let apiTimer = null;
        let startTime = 0;
        let currentProgress = 0;

        // DOM 元素获取
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const imagePlaceholder = document.getElementById('imagePlaceholder');
        const inputImageContainer = document.getElementById('inputImageContainer');
        const resultImageContainer = document.getElementById('resultImageContainer');
        const promptDisplay = document.getElementById('promptDisplay');
        const promptTextarea = document.getElementById('promptTextarea');
        const timeIndicator = document.getElementById('timeIndicator');
        const progressFill = document.getElementById('progressFill');
        const apiStatus = document.getElementById('apiStatus');
        const apiResponse = document.getElementById('apiResponse');
        const apiResponseContent = document.getElementById('apiResponseContent');
        const createVideoBtn = document.getElementById('createVideoBtn');
        const generateBtn = document.getElementById('generateBtn');
        const resetAllBtn = document.getElementById('resetAllBtn');
        const resetBtn = document.getElementById('resetBtn');
        const closeBtn = document.getElementById('closeBtn');
        const wideAngleCheckbox = document.getElementById('wideAngleCheckbox');
        const horizontalSlider = document.getElementById('horizontalSlider');
        const verticalMoveSlider = document.getElementById('verticalMoveSlider');
        const rotateSlider = document.getElementById('rotateSlider');
        const moveSlider = document.getElementById('moveSlider');
        const verticalSlider = document.getElementById('verticalSlider');
        const horizontalInput = document.getElementById('horizontalInput');
        const verticalMoveInput = document.getElementById('verticalMoveInput');
        const rotateInput = document.getElementById('rotateInput');
        const moveInput = document.getElementById('moveInput');
        const verticalInput = document.getElementById('verticalInput');
        const resetBtns = document.querySelectorAll('.reset-btn');
        const urlInput = document.getElementById('urlInput');
        const loadUrlBtn = document.getElementById('loadUrlBtn');
        const urlStatus = document.getElementById('urlStatus');
        const apiKeyInput = document.getElementById('apiKeyInput');
        const saveApiKeyBtn = document.getElementById('saveApiKeyBtn');

        // 初始化状态
        function init() {
            // 设置默认值
            updateSliders();
            updateTooltips();

            // 绑定事件
            bindEvents();

            // 初始化提示词显示
            updatePrompt();

            // 检查是否有保存的图像
            checkSavedImage();

            // 加载保存的API密钥
            loadSavedApiKey();
        }

        // 绑定所有事件
        function bindEvents() {
            // 上传区域点击事件
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });

            // 文件选择事件
            fileInput.addEventListener('change', handleFileSelect);

            // 拖拽事件
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = 'var(--primary-color)';
                uploadArea.style.backgroundColor = 'rgba(255, 179, 0, 0.1)';
            });

            uploadArea.addEventListener('dragleave', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#555';
                uploadArea.style.backgroundColor = '';
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#555';
                uploadArea.style.backgroundColor = '';

                if (e.dataTransfer.files.length > 0) {
                    handleFileDrop(e.dataTransfer.files[0]);
                }
            });

            // 控制器滑块和输入框同步
            horizontalSlider.addEventListener('input', updateHorizontalInput);
            horizontalInput.addEventListener('input', updateHorizontalSlider);
            verticalMoveSlider.addEventListener('input', updateVerticalMoveInput);
            verticalMoveInput.addEventListener('input', updateVerticalMoveSlider);
            rotateSlider.addEventListener('input', updateRotateInput);
            rotateInput.addEventListener('input', updateRotateSlider);
            moveSlider.addEventListener('input', updateMoveInput);
            moveInput.addEventListener('input', updateMoveSlider);
            verticalSlider.addEventListener('input', updateVerticalInput);
            verticalInput.addEventListener('input', updateVerticalSlider);

            // 控制器变化时更新提示词
            horizontalSlider.addEventListener('input', updatePrompt);
            horizontalInput.addEventListener('input', updatePrompt);
            verticalMoveSlider.addEventListener('input', updatePrompt);
            verticalMoveInput.addEventListener('input', updatePrompt);
            rotateSlider.addEventListener('input', updatePrompt);
            rotateInput.addEventListener('input', updatePrompt);
            moveSlider.addEventListener('input', updatePrompt);
            moveInput.addEventListener('input', updatePrompt);
            verticalSlider.addEventListener('input', updatePrompt);
            verticalInput.addEventListener('input', updatePrompt);

            // 复位按钮
            resetBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const targetId = btn.getAttribute('data-target');
                    const targetInput = document.getElementById(targetId);
                    const targetSlider = document.getElementById(targetId.replace('Input', 'Slider'));

                    if (targetId === 'horizontalInput') {
                        targetInput.value = '0';
                        targetSlider.value = '0';
                    } else if (targetId === 'verticalMoveInput') {
                        targetInput.value = '0';
                        targetSlider.value = '0';
                    } else if (targetId === 'rotateInput') {
                        targetInput.value = '0';
                        targetSlider.value = '0';
                    } else if (targetId === 'moveInput') {
                        targetInput.value = '0';
                        targetSlider.value = '0';
                    } else if (targetId === 'verticalInput') {
                        targetInput.value = '0';
                        targetSlider.value = '0';
                    }

                    updateTooltips();
                    updatePrompt();
                });
            });

            // 宽角镜头复选框
            wideAngleCheckbox.addEventListener('click', function(e) {
                e.preventDefault();
                toggleWideAngle();
                updatePrompt();
            });

            // 生成按钮
            generateBtn.addEventListener('click', generateImage);

            // 重置所有按钮
            resetAllBtn.addEventListener('click', resetAllControls);

            // 重置按钮
            resetBtn.addEventListener('click', resetImage);

            // 关闭按钮
            closeBtn.addEventListener('click', closeImage);

            // 创建视频按钮
            createVideoBtn.addEventListener('click', createVideo);

            // URL加载按钮
            loadUrlBtn.addEventListener('click', loadImageFromUrl);

            // URL输入框回车键支持
            urlInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    loadImageFromUrl();
                }
            });

            // API密钥保存按钮
            saveApiKeyBtn.addEventListener('click', saveApiKey);

            // API密钥输入框回车键支持
            apiKeyInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    saveApiKey();
                }
            });

            // 监听窗口大小变化
            window.addEventListener('resize', updateLayout);
        }

        // 处理文件选择
        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                handleFileDrop(file);
            }
        }

        // 处理文件拖放
        function handleFileDrop(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                selectedImage = e.target.result;
                displayImage(selectedImage);
                saveImageToStorage(selectedImage);
            };
            reader.readAsDataURL(file);
        }

        // 显示图像
        function displayImage(src) {
            // 清除占位符
            imagePlaceholder.style.display = 'none';

            // 创建图像元素
            const img = document.createElement('img');
            img.src = src;
            img.alt = 'Uploaded Image';
            img.id = 'inputImage';

            // 清除容器内容
            inputImageContainer.innerHTML = '';
            inputImageContainer.appendChild(img);

            // 添加预览操作层
            const previewOverlay = document.createElement('div');
            previewOverlay.className = 'preview-overlay';
            previewOverlay.innerHTML = `
                <div class="preview-action" id="zoomAction">🔍</div>
                ${!src.startsWith('http') ? `<div class="preview-action" id="rotateAction">🔄</div>` : ''}
            `;
            inputImageContainer.appendChild(previewOverlay);

            // 绑定预览操作事件
            document.getElementById('zoomAction').addEventListener('click', () => {
                zoomImage();
            });

            if (!src.startsWith('http')) {
                document.getElementById('rotateAction').addEventListener('click', () => {
                    rotateImage();
                });
            }
        }

        // 更新滑块值
        function updateSliders() {
            horizontalSlider.value = horizontalInput.value;
            verticalMoveSlider.value = verticalMoveInput.value;
            rotateSlider.value = rotateInput.value;
            moveSlider.value = moveInput.value;
            verticalSlider.value = verticalInput.value;
        }

        // 更新提示文本
        function updateTooltips() {
            document.getElementById('horizontalTooltip').textContent = horizontalInput.value;
            document.getElementById('verticalMoveTooltip').textContent = verticalMoveInput.value;
            document.getElementById('rotateTooltip').textContent = `${rotateInput.value}°`;
            document.getElementById('moveTooltip').textContent = moveInput.value;
            document.getElementById('verticalTooltip').textContent = verticalInput.value;
        }

        // 同步旋转滑块和输入框
        function updateRotateInput() {
            rotateInput.value = rotateSlider.value;
            updateTooltips();
        }

        function updateRotateSlider() {
            rotateSlider.value = rotateInput.value;
            updateTooltips();
        }

        // 同步移动滑块和输入框
        function updateMoveInput() {
            moveInput.value = moveSlider.value;
            updateTooltips();
        }

        function updateMoveSlider() {
            moveSlider.value = moveInput.value;
            updateTooltips();
        }

        // 同步左右移动滑块和输入框
        function updateHorizontalInput() {
            horizontalInput.value = horizontalSlider.value;
            updateTooltips();
        }

        function updateHorizontalSlider() {
            horizontalSlider.value = horizontalInput.value;
            updateTooltips();
        }

        // 同理上下移动滑块和输入框
        function updateVerticalMoveInput() {
            verticalMoveInput.value = verticalMoveSlider.value;
            updateTooltips();
        }

        function updateVerticalMoveSlider() {
            verticalMoveSlider.value = verticalMoveInput.value;
            updateTooltips();
        }

        // 同步垂直角度滑块和输入框
        function updateVerticalInput() {
            verticalInput.value = verticalSlider.value;
            updateTooltips();
        }

        function updateVerticalSlider() {
            verticalSlider.value = verticalInput.value;
            updateTooltips();
        }

        // 更新提示词显示
        function updatePrompt() {
            const horizontalValue = parseFloat(horizontalInput.value);
            const verticalMoveValue = parseFloat(verticalMoveInput.value);
            const rotateValue = parseInt(rotateInput.value);
            const moveValue = parseInt(moveInput.value);
            const verticalValue = parseFloat(verticalInput.value);
            const isWideAngle = wideAngleCheckbox.querySelector('.checkbox').classList.contains('checked');

            let lines = [];

            // 根据滑块值构建提示词
            if (horizontalValue < 0) {
                lines.push(`将镜头向左移动（Move the camera left.）`);
            } else if (horizontalValue > 0) {
                lines.push(`将镜头向右移动（Move the camera right.）`);
            }

            if (verticalMoveValue < 0) {
                lines.push(`将镜头向下移动（Move the camera down.）`);
            } else if (verticalMoveValue > 0) {
                lines.push(`将镜头向上移动（Move the camera up.）`);
            }

            if (rotateValue < 0) {
                lines.push(`将镜头向左旋转${Math.abs(rotateValue)}度（Rotate the camera ${Math.abs(rotateValue)} degrees to the left.）`);
            } else if (rotateValue > 0) {
                lines.push(`将镜头向右旋转${rotateValue}度（Rotate the camera ${rotateValue} degrees to the right.）`);
            }

            if (moveValue > 0) {
                if (moveValue >= 10) {
                    lines.push(`将镜头转为特写镜头（Turn the camera to a close-up.）`);
                } else {
                    lines.push(`将镜头向前移动${moveValue}单位（Move the camera ${moveValue} units forward.）`);
                }
            }

            if (verticalValue < 0) {
                lines.push(`将镜头转为俯视（Turn the camera to a top-down view.）`);
            } else if (verticalValue > 0) {
                lines.push(`将镜头转为仰视（Turn the camera to a bottom-up view.）`);
            }

            if (isWideAngle) {
                lines.push(`将镜头转为广角镜头（Turn the camera to a wide-angle lens.）`);
            }

            // 如果没有设置任何参数，显示默认提示
            if (lines.length === 0) {
                lines.push('调整摄像机控制器，这里将显示对应的文字提示词，也可以手动编辑...');
            }

            // 直接更新文本框内容，实时显示提示词
            promptTextarea.value = lines.join('\n');
        }

        // 切换宽角镜头
        function toggleWideAngle() {
            const checkbox = wideAngleCheckbox.querySelector('.checkbox');
            const isChecked = checkbox.classList.contains('checked');

            if (isChecked) {
                checkbox.classList.remove('checked');
                checkbox.innerHTML = '';
            } else {
                checkbox.classList.add('checked');
                checkbox.innerHTML = '<div class="checkbox-icon">✓</div>';
            }
        }

        // 从URL加载图像
        function loadImageFromUrl() {
            const url = urlInput.value.trim();
            if (!url) {
                showUrlStatus('请输入有效的URL地址', 'error');
                return;
            }

            // 简单的URL验证
            try {
                new URL(url);
            } catch {
                showUrlStatus('请输入有效的URL地址', 'error');
                return;
            }

            showUrlStatus('正在加载图片...', 'loading');

            // 预加载图片以验证URL有效性
            const img = new Image();
            img.crossOrigin = 'anonymous'; // 尝试解决跨域问题

            img.onload = function() {
                selectedImage = url;
                displayImage(url);
                saveImageToStorage(url);
                showUrlStatus('图片加载成功', 'success');
            };

            img.onerror = function() {
                showUrlStatus('图片加载失败，请检查URL是否正确', 'error');
            };

            img.src = url;
        }

        // 显示URL状态信息
        function showUrlStatus(message, type) {
            urlStatus.textContent = message;
            urlStatus.style.display = 'block';
            urlStatus.className = 'info-text';

            if (type === 'error') {
                urlStatus.style.color = '#F44336';
            } else if (type === 'success') {
                urlStatus.style.color = '#4CAF50';
            } else {
                urlStatus.style.color = '#FF9800';
            }
        }

        // 生成图像
        function generateImage() {
            // 检查是否有图片（本地或URL）
            if (!selectedImage) {
                alert('请先上传一张图片或输入URL地址！');
                return;
            }

            if (isProcessing) {
                alert('正在处理中，请稍后再试！');
                return;
            }

            // 开始处理
            startProcessing();

            // 获取提示词文本框中的内容
            const promptText = promptTextarea.value;

            // 显示提示词
            promptDisplay.innerHTML = `<pre style="white-space: pre-wrap; font-size: 14px; line-height: 1.5;">${promptText}</pre>`;

            // 检查图片类型并传递正确的格式给API
            const imageSource = selectedImage;
            let imageParam = '';

            if (imageSource.startsWith('http')) {
                // 网络图片URL，直接传递URL
                imageParam = imageSource;
            } else {
                // 本地图片，转换为base64（不带前缀）
                const base64Image = getImageAsBase64();
                imageParam = base64Image;
            }

            console.log('图片类型:', imageSource.startsWith('http') ? 'URL' : '本地');
            console.log('图片参数:', imageParam ? '有参数' : '无参数');

            // 使用requestAnimationFrame避免阻塞UI
            requestAnimationFrame(() => {
                callRealApi(promptText, imageParam);
            });
        }

        // 保存图像到本地文件并返回文件路径
        function saveImageToFile() {
            const imgElement = document.getElementById('inputImage');
            if (!imgElement) {
                return '';
            }

            try {
                // 创建canvas
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // 设置canvas尺寸，限制最大尺寸以提高性能
                const maxSize = 1024; // 最大尺寸
                let { width, height } = imgElement;

                if (width > maxSize || height > maxSize) {
                    const ratio = Math.min(maxSize / width, maxSize / height);
                    width *= ratio;
                    height *= ratio;
                }

                canvas.width = width;
                canvas.height = height;

                // 绘制图像
                ctx.drawImage(imgElement, 0, 0, width, height);

                // 转换为blob文件
                canvas.toBlob(function(blob) {
                    if (!blob) {
                        console.error('图像转换失败');
                        return;
                    }

                    // 创建文件名
                    const timestamp = new Date().getTime();
                    const filename = `camera_${timestamp}.jpg`;

                    // 创建下载链接
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;

                    // 触发下载
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);

                    // 清理URL
                    setTimeout(() => URL.revokeObjectURL(url), 100);

                    console.log('图片已保存为:', filename);
                }, 'image/jpeg', 0.8);

                return '';

            } catch (error) {
                console.error('图像转换失败:', error);
                return '';
            }
        }

        // 将图像转换为base64编码（备用方法）
        function getImageAsBase64() {
            const imgElement = document.getElementById('inputImage');
            if (!imgElement) {
                console.log('未找到图片元素');
                return '';
            }

            console.log('图片元素存在，src:', imgElement.src ? '有值' : '无值');

            try {
                // 创建canvas
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // 设置canvas尺寸，限制最大尺寸以提高性能
                const maxSize = 1024; // 最大尺寸
                let { width, height } = imgElement;

                console.log('原始图片尺寸:', width, 'x', height);

                if (width > maxSize || height > maxSize) {
                    const ratio = Math.min(maxSize / width, maxSize / height);
                    width *= ratio;
                    height *= ratio;
                    console.log('缩放后尺寸:', width, 'x', height);
                }

                canvas.width = width;
                canvas.height = height;

                // 绘制图像
                ctx.drawImage(imgElement, 0, 0, width, height);

                // 转换为base64，使用JPEG格式以获得更好的压缩
                const base64Image = canvas.toDataURL('image/jpeg', 0.8);

                // 返回纯base64数据（不带data URI前缀）
                const base64Data = base64Image.split(',')[1];

                console.log('Base64数据长度:', base64Data ? base64Data.length : 0);

                return base64Data;

            } catch (error) {
                console.error('图像转换失败:', error);
                return '';
            }
        }

        // 开始处理
        function startProcessing() {
            isProcessing = true;
            startTime = Date.now();
            currentProgress = 0;

            // 重置进度条
            progressFill.style.width = '0%';

            // 显示时间指示器和进度条
            timeIndicator.style.display = 'block';
            document.querySelector('.progress-bar').style.display = 'block';
            timeIndicator.textContent = 'processing | 0.0/?.?s';

            // 设置处理中状态样式
            apiStatus.className = 'api-status processing';
            apiStatus.textContent = 'API 状态: 处理中';

            // 设置定时器更新进度
            apiTimer = setInterval(() => {
                currentProgress += 5;
                if (currentProgress > 100) {
                    currentProgress = 100;
                    clearInterval(apiTimer);
                }
                progressFill.style.width = `${currentProgress}%`;
            }, 200);
        }

        // 更新时间指示器
        function updateTimeIndicator() {
            const now = Date.now();
            const elapsed = Math.floor((now - startTime) / 1000);
            const total = 3.9; // 模拟总时间
            
            if (elapsed >= total) {
                timeIndicator.textContent = `completed | ${total}s`;
            } else {
                timeIndicator.textContent = `processing | ${elapsed.toFixed(1)}/${total}s`;
            }
        }

        // 真实API调用
        async function callRealApi(prompt, imageParam = '') {
            try {
                // 检查API密钥
                const apiKey = getApiKey();
                if (!apiKey) {
                    throw new Error('未配置API密钥，请先在页面加载时输入API密钥或通过URL参数传递api_key');
                }

                // 准备API请求数据 - 使用BizyAIR API格式
                let imageData;
                if (imageParam.startsWith('http')) {
                    // 网络图片URL，直接使用
                    imageData = imageParam;
                    console.log('使用网络图片URL:', imageParam);
                } else if (imageParam.startsWith('data:image')) {
                    // base64图片，提取base64部分
                    imageData = imageParam;
                    console.log('使用base64图片格式');
                } else if (imageParam) {
                    // 纯base64数据，添加data URI前缀
                    imageData = `data:image/jpeg;base64,${imageParam}`;
                    console.log('使用纯base64数据，已添加前缀');
                } else {
                    throw new Error('未提供有效的图片参数');
                }

                const apiData = {
                    web_app_id: 38783,
                    suppress_preview_output: true,
                    input_values: {
                        "11:TextEncodeQwenImageEditPlus.prompt": prompt,
                        "31:LoadImage.image": imageData,
                        "14:KSampler.steps": 4
                    }
                };

                // 显示API调用状态
                apiStatus.className = 'api-status processing';
                apiStatus.textContent = 'API 状态: 调用中...';

                console.log('API请求数据:', JSON.stringify(apiData, null, 2));
                console.log('API密钥:', apiKey.substring(0, 10) + '...');

                // 发送API请求到真实的BizyAIR API
                console.log('发送API请求...');
                const response = await fetch('https://api.bizyair.cn/w/v1/webapp/task/openapi/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + apiKey
                    },
                    body: JSON.stringify(apiData)
                });

                console.log('API响应状态:', response.status, response.statusText);

                // 检查响应状态
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP错误! 状态: ${response.status}, 响应: ${errorText}`);
                }

                // 解析响应数据
                const responseData = await response.json();
                console.log('API响应数据:', JSON.stringify(responseData, null, 2));

                // 更新API状态
                if (responseData.status === 'Success') {
                    apiStatus.textContent = 'API 状态: 成功';
                    apiStatus.className = 'api-status success';
                } else {
                    apiStatus.textContent = `API 状态: 失败 - ${responseData.message || '未知错误'}`;
                    apiStatus.className = 'api-status error';
                }

                // 结束处理
                endProcessing({
                    success: responseData.status === 'Success',
                    message: responseData.message,
                    api_response: responseData,
                    outputs: responseData.outputs
                });

            } catch (error) {
                console.error('API调用失败:', error);

                // 显示错误状态
                apiStatus.textContent = `API 状态: 失败 - ${error.message}`;
                apiStatus.className = 'api-status error';

                // 显示错误响应
                const errorResponse = {
                    success: false,
                    message: error.message,
                    type: 'ERROR',
                    status: 'Failed',
                    created_at: new Date().toLocaleString(),
                    error: error.toString()
                };

                endProcessing(errorResponse);
            }
        }

        // 保存API密钥
        function saveApiKey() {
            const apiKey = apiKeyInput.value.trim();
            if (!apiKey) {
                alert('请输入API密钥');
                return;
            }

            try {
                // 保存到localStorage
                localStorage.setItem('bizyair_api_key', apiKey);

                // 保存到cookie
                const expires = new Date();
                expires.setTime(expires.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30天
                document.cookie = `BIZY_KEY=${apiKey};expires=${expires.toUTCString()};path=/`;

                console.log('API密钥已保存');

                // 显示成功提示
                const statusMsg = document.createElement('div');
                statusMsg.textContent = '✓ API密钥已保存';
                statusMsg.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #4CAF50;
                    color: white;
                    padding: 10px 20px;
                    border-radius: 4px;
                    z-index: 10001;
                    font-size: 14px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
                    animation: slideIn 0.3s ease;
                `;
                document.body.appendChild(statusMsg);

                setTimeout(() => {
                    if (document.body.contains(statusMsg)) {
                        document.body.removeChild(statusMsg);
                    }
                }, 3000);

            } catch (error) {
                console.error('保存API密钥失败:', error);
                alert('保存API密钥失败');
            }
        }

        // 加载保存的API密钥
        function loadSavedApiKey() {
            try {
                // 优先从localStorage加载
                const savedApiKey = localStorage.getItem('bizyair_api_key');
                if (savedApiKey) {
                    apiKeyInput.value = savedApiKey;
                    console.log('从localStorage加载API密钥');
                    return;
                }

                // 其次从cookie加载
                const cookies = document.cookie.split(';');
                for (let cookie of cookies) {
                    const [name, value] = cookie.trim().split('=');
                    if (name === 'BIZY_KEY') {
                        apiKeyInput.value = value;
                        localStorage.setItem('bizyair_api_key', value);
                        console.log('从cookie加载API密钥');
                        return;
                    }
                }

                // 最后从URL参数加载
                const urlParams = new URLSearchParams(window.location.search);
                const urlApiKey = urlParams.get('api_key');
                if (urlApiKey) {
                    apiKeyInput.value = urlApiKey;
                    localStorage.setItem('bizyair_api_key', urlApiKey);
                    console.log('从URL参数加载API密钥');
                }
            } catch (error) {
                console.error('加载API密钥失败:', error);
            }
        }

        // 获取API密钥
        function getApiKey() {
            // 优先使用输入框的值
            const inputApiKey = apiKeyInput.value.trim();
            if (inputApiKey) {
                return inputApiKey;
            }

            // 其次从localStorage获取
            const savedApiKey = localStorage.getItem('bizyair_api_key');
            if (savedApiKey) {
                console.log('从localStorage获取API密钥');
                return savedApiKey;
            }

            // 尝试从cookie获取
            const cookies = document.cookie.split(';');
            for (let cookie of cookies) {
                const [name, value] = cookie.trim().split('=');
                if (name === 'BIZY_KEY') {
                    console.log('从cookie获取API密钥');
                    return value;
                }
            }

            // 最后从URL参数获取
            const urlParams = new URLSearchParams(window.location.search);
            const urlApiKey = urlParams.get('api_key');
            if (urlApiKey) {
                console.log('从URL参数获取API密钥');
                return urlApiKey;
            }

            console.warn('未获取到API密钥');
            return '';
        }

        // 结束处理
        function endProcessing(response) {
            console.log('endProcessing 被调用，response:', response);
            isProcessing = false;
            clearInterval(apiTimer);

            // 立即更新基本状态，让页面恢复可操作
            requestAnimationFrame(() => {
                if (response.success) {
                    apiStatus.textContent = 'API 状态: 成功';
                    apiStatus.className = 'api-status success';
                    console.log('API调用成功');
                } else {
                    const statusText = response.message || '失败';
                    apiStatus.textContent = `API 状态: ${statusText}`;
                    apiStatus.className = 'api-status error';
                    console.error('API调用失败:', response);
                }

                // 恢复提示词文本框
                const textarea = document.createElement('div');
                textarea.className = 'prompt-textarea';
                textarea.id = 'promptTextarea';
                textarea.contenteditable = 'true';
                textarea.textContent = promptTextarea.value;
                promptDisplay.innerHTML = '';
                promptDisplay.appendChild(textarea);

                // 隐藏进度条
                timeIndicator.style.display = 'none';
                document.querySelector('.progress-bar').style.display = 'none';

                // 延迟处理图片显示，避免阻塞
                setTimeout(() => {
                    console.log('处理结果图片...');

                    // 检查响应数据结构
                    const outputs = response.outputs || (response.api_response && response.api_response.outputs);
                    console.log('Outputs:', outputs);

                    if (outputs && outputs.length > 0) {
                        const imageUrl = outputs[0].object_url;
                        console.log('获取到图片URL:', imageUrl);

                        // 先显示图片
                        displayResultImage(imageUrl);

                        // 图片加载完成后，设置弹窗显示
                        setTimeout(() => {
                            const imgElement = document.getElementById('resultImage');
                            if (imgElement && imgElement.src === imageUrl) {
                                // 弹窗显示图片
                                showImagePopup(imageUrl);
                            }
                        }, 1000); // 等待1秒确保图片加载完成
                    } else {
                        console.warn('响应中没有outputs数据');
                        resultImageContainer.innerHTML = '<div class="image-placeholder"><div>❌</div><div>生成失败 - 无返回数据</div></div>';

                        // 显示更多调试信息
                        if (response.api_response) {
                            console.log('完整API响应:', response.api_response);
                        }
                    }

                    // 只有失败时才显示API响应信息
                    const apiResponse = document.getElementById('apiResponse');
                    if (!response.success) {
                        apiResponse.style.display = 'block';

                        // 使用 setTimeout 处理 JSON.stringify
                        setTimeout(() => {
                            const formattedResponse = {
                                type: response.type || 'API',
                                success: response.success,
                                message: response.message,
                                api_response: response.api_response,
                                outputs: response.outputs,
                                request_id: response.api_response?.request_id,
                                cost_time: response.api_response?.cost_time
                            };
                            apiResponseContent.textContent = JSON.stringify(formattedResponse, null, 2);
                        }, 10);
                    } else {
                        apiResponse.style.display = 'none';
                    }
                }, 100);
            });
        }

        // 显示结果图像
        function displayResultImage(src) {
            // 使用 requestAnimationFrame 确保不阻塞UI
            requestAnimationFrame(() => {
                // 清除容器内容
                resultImageContainer.innerHTML = '';

                // 显示加载状态
                const loadingDiv = document.createElement('div');
                loadingDiv.className = 'image-placeholder';
                loadingDiv.innerHTML = `
                    <div class="loading-spinner"></div>
                    <div>正在加载生成结果...</div>
                `;
                resultImageContainer.appendChild(loadingDiv);

                // 创建图像元素
                const img = document.createElement('img');
                img.src = src;
                img.alt = 'Generated Image';
                img.id = 'resultImage';
                img.style.width = '100%';
                img.style.height = 'auto';
                img.style.objectFit = 'cover';
                img.style.borderRadius = '8px';

                img.onload = () => {
                    // 使用 setTimeout 延迟显示图片，让UI先响应
                    setTimeout(() => {
                        // 清除加载状态
                        resultImageContainer.innerHTML = '';

                        // 添加图片
                        resultImageContainer.appendChild(img);

                    }, 50);
                };

                img.onerror = () => {
                    setTimeout(() => {
                        resultImageContainer.innerHTML = '<div class="image-placeholder"><div>❌</div><div>图像加载失败</div></div>';
                    }, 50);
                };

                // 如果图片已经缓存，onload 可能不会触发，手动触发
                if (img.complete) {
                    img.onload();
                }
            });
        }

        // 重置所有控制器
        function resetAllControls() {
            horizontalInput.value = '0';
            verticalMoveInput.value = '0';
            rotateInput.value = '0';
            moveInput.value = '0';
            verticalInput.value = '0';
            updateSliders();
            updateTooltips();

            // 重置宽角镜头
            const checkbox = wideAngleCheckbox.querySelector('.checkbox');
            checkbox.classList.remove('checked');
            checkbox.innerHTML = '';

            // 更新提示词
            updatePrompt();
        }

        // 重置图像
        function resetImage() {
            if (selectedImage) {
                displayImage(selectedImage);
            }
        }

        // 关闭图像
        function closeImage() {
            selectedImage = null;
            inputImageContainer.innerHTML = '';
            imagePlaceholder.style.display = 'flex';
            urlInput.value = '';
            showUrlStatus('', '');
            clearImageFromStorage();
        }

        // 显示图片弹窗
        function showImagePopup(imageUrl) {
            // 移除现有弹窗
            const existingPopup = document.getElementById('imageModal');
            if (existingPopup) {
                document.body.removeChild(existingPopup);
            }

            // 创建弹窗元素
            const modal = document.createElement('div');
            modal.id = 'imageModal';
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.9);
                z-index: 10000;
                display: flex;
                align-items: center;
                justify-content: center;
                animation: fadeIn 0.3s ease;
            `;

            // 创建图片容器
            const imageContainer = document.createElement('div');
            imageContainer.style.cssText = `
                position: relative;
                max-width: 90%;
                max-height: 90%;
                display: flex;
                align-items: center;
                justify-content: center;
            `;

            // 创建图片元素
            const img = document.createElement('img');
            img.src = imageUrl;
            img.alt = 'Generated Image';
            img.style.cssText = `
                max-width: 100%;
                max-height: 80vh;
                object-fit: contain;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
            `;

            // 创建关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.textContent = '✕';
            closeBtn.style.cssText = `
                position: absolute;
                top: -40px;
                right: -40px;
                background: rgba(255, 255, 255, 0.2);
                color: white;
                border: none;
                width: 40px;
                height: 40px;
                border-radius: 50%;
                font-size: 20px;
                cursor: pointer;
                transition: all 0.3s ease;
            `;

            closeBtn.addEventListener('click', () => {
                document.body.removeChild(modal);
            });

            closeBtn.addEventListener('mouseover', () => {
                closeBtn.style.background = 'rgba(255, 255, 255, 0.3)';
            });

            closeBtn.addEventListener('mouseout', () => {
                closeBtn.style.background = 'rgba(255, 255, 255, 0.2)';
            });

            // 添加点击弹窗外部关闭功能
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    document.body.removeChild(modal);
                }
            });

            // 添加键盘事件监听
            const handleKeyPress = (e) => {
                if (e.key === 'Escape') {
                    if (document.body.contains(modal)) {
                        document.body.removeChild(modal);
                    }
                    document.removeEventListener('keydown', handleKeyPress);
                }
            };
            document.addEventListener('keydown', handleKeyPress);

            // 组装弹窗
            imageContainer.appendChild(img);
            imageContainer.appendChild(closeBtn);
            modal.appendChild(imageContainer);
            document.body.appendChild(modal);

            console.log('图片弹窗已显示');
        }

  
    
        // 创建视频
        function createVideo() {
            if (!selectedImage) {
                alert('请先上传一张图片！');
                return;
            }
            
            // 模拟创建视频请求
            alert('视频制作申请功能即将上线！\n\n当前版本仅支持图像处理功能。\n\n我们将为您保存当前设置，待功能开放后自动处理。');
            
            // 在实际应用中，这里应该调用视频制作API
            // 保存当前状态以便后续处理
            saveCurrentState();
        }

        // 保存当前状态
        function saveCurrentState() {
            const state = {
                selectedImage: selectedImage,
                controls: {
                    rotate: rotateInput.value,
                    move: moveInput.value,
                    vertical: verticalInput.value,
                    wideAngle: wideAngleCheckbox.querySelector('.checkbox').classList.contains('checked')
                },
                timestamp: Date.now()
            };
            
            // 在实际应用中，可以保存到服务器或本地存储
            console.log('保存当前状态:', state);
        }

    
        // 更新布局
        function updateLayout() {
            // 调整图像容器高度以适应屏幕尺寸
            const containerHeight = window.innerHeight - 100;
            const imageContainer = document.querySelector('.image-container');
            const resultContainer = document.querySelector('.result-image');
            
            if (imageContainer) {
                imageContainer.style.height = `${Math.min(containerHeight, 300)}px`;
            }
            
            if (resultContainer) {
                resultContainer.style.height = `${Math.min(containerHeight, 300)}px`;
            }
        }

        // 保存图像到本地存储
        function saveImageToStorage(imageData) {
            try {
                const storageData = {
                    source: imageData,
                    type: imageData.startsWith('http') ? 'url' : 'local',
                    timestamp: Date.now()
                };
                localStorage.setItem('savedImage', JSON.stringify(storageData));
            } catch (e) {
                console.warn('无法保存图像到本地存储:', e);
            }
        }

        // 从本地存储检查并加载图像
        function checkSavedImage() {
            try {
                const savedData = localStorage.getItem('savedImage');
                if (savedData) {
                    const storageData = JSON.parse(savedData);
                    selectedImage = storageData.source;
                    displayImage(storageData.source);
                }
            } catch (e) {
                console.warn('无法从本地存储加载图像:', e);
            }
        }

        // 清除图像从本地存储
        function clearImageFromStorage() {
            try {
                localStorage.removeItem('savedImage');
            } catch (e) {
                console.warn('无法清除图像从本地存储:', e);
            }
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>